package homework;

import java.util.Scanner;

/**
 * @classname:Main
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/7 11:44
 * @version: 0.1
 * @since:1.8
 */
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.println("请输入一个字符串");
            String numStr = input.next();
            int i = stringToInt(numStr);
            System.out.println(i);
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
    }

    private static int stringToInt(String numStr) {
        if (numStr == null) return -1;
        if (numStr.length() == 0) return -1;
        int len = numStr.length();
        boolean flag = false;
        int result = 0;
        for (int i = 0; i < len; i++) {
            if (numStr.charAt(0) == '-') {
                flag = true;
                for (int j = 1; j < len; j++) {
                    char num1 = numStr.charAt(j);
                    boolean res = Character.isDigit(num1);
                    if (!res)
                        throw new NumberFormatException("输入格式错误");
                    int digit = num1 - 48;
                    result = result * 10 + digit;
                }
                break;
            }
            char charnum1 = numStr.charAt(i);
            boolean res1 = Character.isDigit(charnum1);
            if (!res1)
                throw new NumberFormatException("输入格式错误");
            int digit = charnum1 - 48;
            result = result * 10 + digit;
        }
        return flag ? -result : result;
    }
}
